package com.jasonflaherty.inciweb;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.XmlDom;

public class MainActivity extends SherlockActivity {

	private AQuery aq;
	private ProgressDialog dialog;
	private static final String TAG = "INCIWEB";
	private ListView lv;
	protected Object IncidentAdapter;
	EditText inputSearch;
	String url;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		getSupportActionBar().setDisplayHomeAsUpEnabled(false);
		getSupportActionBar().setSubtitle("Incidents across the USA");
		aq = new AQuery(this);
		dialog = new ProgressDialog(this);
		dialog.setCancelable(true);
		dialog.setInverseBackgroundForced(false);
		dialog.setCanceledOnTouchOutside(true);
		dialog.setMessage("Fetching Latest...");

		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.USStates, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

		Spinner s = (Spinner) findViewById(R.id.stateSpinner);
		s.setAdapter(adapter);

		s.setPrompt("Select a location...");

		final String USStates = s.getSelectedItem().toString();
		Log.e("STATE", USStates);

		s.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parentView,
					View selectedItemView, int position, long id) {
				try {
					getFeed(position);
				} catch (Exception e) {
					Log.e(TAG, e.getMessage());
				}
			}

			@Override
			public void onNothingSelected(AdapterView<?> parentView) {

			}

		});

	}

	public void getFeed(int num) {
		if (num == 0) {
			// latest updates - front page
			url = "http://inciweb.org/feeds/rss/incidents/";
		} else {
			// states
			url = "http://inciweb.org/feeds/rss/incidents/state/" + num + "/";
		}

		Log.e("URL", url);
		long expire = -1;
		aq.progress(dialog).ajax(url, XmlDom.class, expire, this,
				"getFeedCallback");
	}

	public void getFeedCallback(String url, XmlDom xml, AjaxStatus status) {
		List<XmlDom> entries = xml.tags("item");
		final List<Incidents> incidents = new ArrayList<Incidents>();
		for (XmlDom entry : entries) {
			incidents.add(new Incidents(entry.text("title"),
					entry.text("link"), entry.text("description"), entry
							.text("published"), entry.text("geo:lat"), entry
							.text("geo:long"), entry.text("georss:point")));
		}

		lv = (ListView) findViewById(R.id.list);
		lv.setTextFilterEnabled(true);
		lv.setAdapter(new IncidentAdapter(this,
				android.R.layout.simple_list_item_1, incidents));

		lv.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View view,
					int position, long id) {

				String ititle = incidents.get(position).getTitle();
				String idesc = incidents.get(position).getDescription();
				String ilink = incidents.get(position).getLink();
				String ipub = incidents.get(position).getPublished();
				String igeoLat = incidents.get(position).getGeoLat();
				String igeoLon = incidents.get(position).getGeoLon();
				String igeoPos = incidents.get(position).getGeoLatLon();

				Toast.makeText(MainActivity.this, id + " clicked",
						Toast.LENGTH_SHORT).show();

				Intent i = new Intent(getApplicationContext(),
						SingleIncident.class);
				i.putExtra("title", ititle).putExtra("desc", idesc)
						.putExtra("link", ilink);
				startActivity(i);
			}
		});

	}

	private class IncidentAdapter extends ArrayAdapter<Incidents> {

		private List<Incidents> items;

		public IncidentAdapter(Context context, int textViewResourceId,
				List<Incidents> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		// Create a title and detail
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.incidents_item, null);
			}
			Incidents o = items.get(position);
			if (o != null) {
				TextView title = (TextView) v.findViewById(R.id.title);
				TextView published = (TextView) v.findViewById(R.id.published);
				TextView link = (TextView) v.findViewById(R.id.link);
				TextView description = (TextView) v
						.findViewById(R.id.description);
				TextView geoLat = (TextView) v.findViewById(R.id.geoLat);
				TextView geoLon = (TextView) v.findViewById(R.id.geoLon);
				TextView geoLatLon = (TextView) v.findViewById(R.id.geoLatLon);

				if (title != null) {
					title.setText(o.getTitle());
				}
				if (published != null) {
					published.setText(o.getPublished());
				}
				if (link != null) {
					link.setText(o.getLink());
				}
				if (description != null) {
					description.setText(o.getDescription());
				}
				if (geoLat != null) {
					geoLat.setText(o.getGeoLat());
				}
				if (geoLon != null) {
					geoLon.setText(o.getGeoLon());
				}
				if (geoLatLon != null) {
					geoLatLon.setText(o.getGeoLatLon());
				}
			}
			return v;
		}
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		com.actionbarsherlock.view.MenuInflater inflater = getSupportMenuInflater();
		inflater.inflate(R.menu.main, (com.actionbarsherlock.view.Menu) menu);
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case android.R.id.home:
			Log.i("MENU", "Home Clicked");
			Intent intentHome = new Intent(getBaseContext(), MainActivity.class);
			intentHome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NO_ANIMATION);
			startActivity(intentHome);
			return true;
		case R.id.map:
			Log.i("MENU", "MAP Clicked");
			Intent imap = new Intent(getBaseContext(), InciwebMapActivity.class);
			imap.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
					| Intent.FLAG_ACTIVITY_NO_ANIMATION);
			startActivity(imap);
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
